package com.wlsk.license.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 *
 * @author taxisys
 */
@Slf4j
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }



    // 将时间戳转换为时间
    public static String stampToDate(Long time){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = new Date(time);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 计算上一天，上一周，上一个月
     * @param dateStr 字符串时间
     * @param DateType 计算计算上一天，上一周，还是上一个月（Calendar.DATE,Calendar.WEEKEND,Calendar.MONTH）
     * @param amount 计算前一天，传-1
     * @return
     * @throws ParseException
     */
    public static String getLastDate(String dateStr, int DateType, int amount) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);//定义日期显示格式
        Calendar c = Calendar.getInstance();
        Date date = sdf.parse(dateStr);
        c.setTime(date);
        c.add(DateType, amount);
        String before = sdf.format(c.getTime());
        return before;
    }

    /**
     * 获取昨天的日期yyyy-MM-dd
     * @return
     */
    public static Date getYesterdayDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
        return dateTime(YYYY_MM_DD, sdf.format(yesterday));
    }

    /**
     * 获取昨天的截止时间
     * @return
     */
    public static Date getYesterdayEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date yesterday = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return dateTime(YYYY_MM_DD_HH_MM_SS, sdf.format(yesterday));
    }

    public static long daysBetween(Date startDate, Date endDate) {
        if(startDate == null || endDate == null) return 0;
        // 计算两个日期之间的天数差
        long diff = endDate.getTime() - startDate.getTime();
        return diff / (24 * 60 * 60 * 1000);
    }

    public static long hoursBetween(Date startDate, Date endDate, RoundingMode roundingMode) {
        if(startDate == null || endDate == null)  return 0;
        // 计算两个日期之间的小时差
        long diffInMillis = endDate.getTime() - startDate.getTime();
        // 将毫秒差值转换为小时,向下取整
        return BigDecimal.valueOf(diffInMillis).divide(BigDecimal.valueOf(60 * 60 * 1000),0, roundingMode).longValue();
    }

    public static long minuteBetween(Date startDate, Date endDate, RoundingMode roundingMode) {
        if(startDate == null || endDate == null)  return 0;
        // 计算两个日期之间的分钟差
        long diffInMillis = endDate.getTime() - startDate.getTime();
        // 将毫秒差值转换为分钟,向下取整
        return BigDecimal.valueOf(diffInMillis).divide(BigDecimal.valueOf(60 * 1000), 0, roundingMode).longValue();
    }

    /**
     * 根据指定的分钟数调整日期时间。
     *
     * @param originalDate 原始日期时间
     * @param minutesToAdjust 要加减的分钟数（正数表示增加，负数表示减少）
     * @return 调整后的新日期时间
     */
    public static Date adjustDateByMinutes(Date originalDate, int minutesToAdjust) {
        // 创建一个Calendar对象，并设置为原始时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(originalDate);

        // 根据指定的分钟数调整时间
        calendar.add(Calendar.MINUTE, minutesToAdjust);

        // 获取新的Date对象
        return calendar.getTime();
    }

    /**
     * 根据指定的天数调整日期时间。
     *
     * @param originalDate 原始日期时间
     * @param days 要加减的天数（正数表示增加，负数表示减少）
     * @return 调整后的新日期时间
     */
    public static Date adjustDateByDays(Date originalDate, int days) {
        // 创建一个Calendar对象，并设置为原始时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(originalDate);

        // 根据指定的天数调整时间
        calendar.add(Calendar.DAY_OF_MONTH, days);

        // 获取新的Date对象
        return calendar.getTime();
    }

    /**
     * 根据传入的Date对象和新增的天数，返回计算后的日期的23:59:59的Date对象
     *
     * @param date       传入的Date对象
     * @param additionalDays 新增的天数
     * @return 返回计算后的日期的23:59:59的Date对象
     */
    public static Date adjustEndOfDayAfterDays(Date date, int additionalDays) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 增加指定的天数
        calendar.add(Calendar.DAY_OF_YEAR, additionalDays);
        // 设置时间为当天的23:59:59
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static int getDateHour(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 去除掉时间中的秒
     * @param date
     * @return
     */
    public static Date delDateSeconds(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 将LocalDateTime格式化为字符串
     */
    public static String formatLocalDateTime(LocalDateTime dateTime, String format) {
        if (dateTime == null) {
            return null;
        }
        DateTimeFormatter FORMATTER =
                DateTimeFormatter.ofPattern(format);
        return dateTime.format(FORMATTER);
    }
}
